<script setup>
import { ref } from 'vue'
import { pcaTextArr } from 'element-china-area-data'
import { getClassApi, getCollegeApi, getMajorApi } from '@/api/baseData'
import { bus } from '@/utils/common/mitt'
import { utils, writeFileXLSX, read } from 'xlsx'
import { useUserStore } from '@/stores/user'

const formRef = ref(null)
const props = defineProps({
  // 表单数据
  data: {
    type: Object,
    default: {}
  },
  formOpt: {
    type: Array,
    default: []
  },
  btnOpt: {
    type: Array,
    default: []
  }
})
const formData = ref(Object.assign({}, props.data))

const emits = defineEmits(['handleForm'])

function handleForm(type) {
  emits('handleForm', type, formData.value)
}
function getValue() {
  return formData.value
}

// 获取学院列表
const collegeList = ref([])
const userStore = useUserStore()
async function getCollegeListData() {
  if (userStore.userInfo.identity === '管理员' && userStore.userInfo.college !== '*') {
    collegeList.value = [
      {
        label: userStore.userInfo.college,
        value: userStore.userInfo.college
      }
    ]
  } else {
    const res = await getCollegeApi()
    collegeList.value = res.data.map((item) => {
      return {
        label: item.college,
        value: item.college
      }
    })
  }
}
getCollegeListData()
// 获取专业列表
const majorList = ref([])
async function getmMajorListData(data) {
  const res = await getMajorApi({ college: data })
  majorList.value = res.data.map((item) => {
    return {
      label: item.major,
      value: item.major
    }
  })
}
// 学院发生变化
function handleCollegeChange(data) {
  // formData.value.major=null
  getmMajorListData(data)
}
const classList = ref([])
// 专业发生变化
async function handleMajorChange(data) {
  const res = await getClassApi({ college: formData.value.college, major: formData.value.major })
  classList.value = res.data?.map((item) => {
    return {
      label: item.class,
      value: item.class
    }
  })
}
bus.on('delete', () => {
  getCollegeListData()
  formData.value.major = null
  formData.value.college = null
})

function handleUpload(e) {
  // 获取上传的文件
  const file = e.file
  // 创建一个FileReader实例
  const reader = new FileReader()
  // 当文件读取完成时触发该函数
  reader.onload = async (e) => {
    // 将读取的结果转换为Uint8Array格式
    const data = new Uint8Array(e.target.result)
    // 使用read函数读取Excel数据
    const workbook = read(data, { type: 'array' })
    // 获取第一个工作表的名称
    const sheetName = workbook.SheetNames[0]
    // 获取第一个工作表
    const worksheet = workbook.Sheets[sheetName]
    // 将工作表转换为JSON格式的数据
    const jsonData = utils.sheet_to_json(worksheet)
    // 这里可将jsonData发送到后端进行进一步处理
    // 调用后端API上传Excel数据，并包含当前日期
    emits('handleForm', 'import', jsonData)
  }
  // 以ArrayBuffer格式读取文件
  reader.readAsArrayBuffer(file)
}
// 点击重置按钮
function reset() {
  formRef.value.resetFields()
  collegeList.value = []
  majorList.value = []
  classList.value = []
  formData.value = {}
}
// 对外提供方法
defineExpose({
  reset,
  getValue
})
</script>

<template>
  <div class="form-wrapper">
    <el-form
      :model="formData"
      :inline="true"
      ref="formRef"
      label-width="auto"
      label-position="left"
      label-suffix="："
    >
      <el-form-item
        v-for="(item, index) in props.formOpt"
        :key="index"
        :label="item.label"
        :prop="item.prop"
      >
        <!-- 身份和普通文本框 -->
        <el-input
          v-model.trim="formData[item.prop]"
          v-if="item.type == 'input'"
          :disabled="item.prop == 'identity'"
        ></el-input>
        <!-- 文本域 -->
        <el-input
          v-model.trim="formData[item.prop]"
          v-if="item.type == 'textarea'"
          :autosize="{ minRows: 2, maxRows: 6 }"
          type="textarea"
          style="width: 195px"
        ></el-input>
        <!-- 密码 -->
        <el-input
          v-model.trim="formData[item.prop]"
          v-if="item.type == 'password'"
          show-password
          type="password"
          style="width: 195px"
        ></el-input>
        <!-- 选择器下拉框 -->
        <el-select
          v-model.trim="formData[item.prop]"
          v-if="item.type == 'select'"
          placeholder="请选择"
          style="width: 195px"
        >
          <el-option
            v-for="obj in item.options"
            :key="obj.value"
            :label="obj.label"
            :value="obj.value"
          />
        </el-select>
        <!-- 地址选择器 -->
        <el-cascader
          v-if="item.type == 'address'"
          style="width: 195px"
          :options="pcaTextArr"
          v-model="formData[item.prop]"
        >
        </el-cascader>
        <!-- 学院选择器 -->
        <el-select
          v-model.trim="formData[item.prop]"
          v-if="item.type == 'selectCollege'"
          placeholder="请选择学院"
          style="width: 195px"
          @change="handleCollegeChange"
        >
          <el-option
            v-for="obj in collegeList"
            :key="obj.value"
            :label="obj.label"
            :value="obj.value"
          />
        </el-select>
        <!-- 专业选择器 -->
        <el-select
          v-model.trim="formData[item.prop]"
          v-if="item.type == 'selectMajor'"
          placeholder="请先选择学院，在选择专业"
          style="width: 230px"
          @change="handleMajorChange"
        >
          <el-option
            v-for="obj in majorList"
            :key="obj.value"
            :label="obj.label"
            :value="obj.value"
          />
        </el-select>
        <!-- 班级选择器 -->
        <el-select
          v-model.trim="formData[item.prop]"
          v-if="item.type == 'selectClass'"
          placeholder="请先选择学院，在选择班级"
          style="width: 230px"
          @change="handleMajorChange"
        >
          <el-option
            v-for="obj in classList"
            :key="obj.value"
            :label="obj.label"
            :value="obj.value"
          />
        </el-select>
      </el-form-item>
      <!-- 操作按钮 -->
      <div style="width: 100%">
        <el-form-item v-for="(item, index) in props.btnOpt" :key="index">
          <!-- 导入 -->
          <el-upload
            style="height: 30px"
            v-if="item.prop === 'import'"
            :http-request="handleUpload"
            action=" "
            :limit="1"
            :show-file-list="false"
          >
            <el-button type="primary" plain style="padding: 0 20px; letter-spacing: 5px"
              >导入</el-button
            >
          </el-upload>
          <el-button
            v-else
            style="padding: 0 20px; letter-spacing: 5px"
            :type="item.btnType || 'primary'"
            @click="handleForm(item.prop)"
            plain
            >{{ item.name }}</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.form-wrapper {
  display: flex;
  justify-content: start;
}

:deep() {
  .el-form-item--label-left .el-form-item__label {
    justify-content: flex-end;
  }
  .el-input {
    box-sizing: border-box;
  }
}
</style>
